from pymongo import MongoClient
from bson import ObjectId

HOST = "192.168.1.36"
PORT = 27017
DB = "flyflyfly"
COLLECTION = "industry_center_channel"

class Dao:
    def __init__(self):
        client = MongoClient(host=HOST, port=PORT)
        self.collection = client[DB][COLLECTION]

    def getRecord(self, id):
        return self.collection.find_one({"_id": ObjectId(id)})


    ## 获取所有记录
    def getRecords(self, page=1, size=10, q=None):
        records = []
        if not q:
            records = self.collection.find(skip=(page - 1) * size, limit=size)
        else:
            records = self.collection.find({"company": {"$regex": q}}, skip=(page - 1) * size, limit=size)
        return records

    ## 增加记录
    def add(self, record):
        result = self.collection.insert_one(record)
        return result

    ## 删除记录
    def delete(self, id):
        result = self.collection.delete_one({"_id": ObjectId(id)})
        return result.acknowledged

    ## 修改记录
    def update(self, id, data):
        result = self.collection.update_one({"_id": ObjectId(id)}, {"$set": data})
        return result.acknowledged

    